package cn.pzaily.orange.core.utils.page;

import cn.pzaily.orange.core.utils.ReflectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @PackageName: cn.pzaily.orange.core.page
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-11 11:57
 */
public class MybatisPageHelper {

    public static final String methodName = "selectPage";

    public static PageResponse selectPage(PageRequest pageRequest, Object mapper) {
        return selectPage(pageRequest, mapper, methodName);
    }

    public static PageResponse selectPage(PageRequest pageRequest, Object mapper, String queryMethodName, Object... args) {
        Integer pageNum = pageRequest.getPageNum();
        Integer pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        Object result = ReflectionUtils.invoke(mapper, queryMethodName, args);
        return getPageResponse(new PageInfo<>((List) result));
    }

    private static PageResponse getPageResponse(PageInfo pageInfo) {
        PageResponse response = new PageResponse();
        response.setPageNum(pageInfo.getPageNum());
        response.setPageSize(pageInfo.getPageSize());
        response.setTotalPageSize(pageInfo.getPages());
        response.setTotalSize(pageInfo.getTotal());
        response.setContent(pageInfo.getList());
        return response;
    }

}
